package com.etennis.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.etennis.constants.AppHttpCodeEnum;
import com.etennis.constants.IOEnum;
import com.etennis.exception.SystemException;
import com.etennis.mapper.MediaMapper;
import com.etennis.mapper.MemberMapper;
import com.etennis.pojos.dto.app.MediaDTO;
import com.etennis.pojos.entity.Media;
import com.etennis.pojos.entity.Member;
import com.etennis.pojos.vo.app.MediaVO;
import com.etennis.service.IMediaService;
import com.etennis.utils.BeanCopyUtils;
import com.etennis.utils.IOUtils;
import com.etennis.utils.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Service
public class MediaServiceImpl extends ServiceImpl<MediaMapper, Media> implements IMediaService {
    @Autowired
    MediaMapper mediaMapper;
    @Autowired
    MemberMapper memberMapper;
    @Autowired
    IOUtils ioUtils;

    @Override
    public void saveMedia(MediaDTO mediaDTO) {
        for (MultipartFile file : mediaDTO.getFiles()) {
            Media media=BeanCopyUtils.copyBean(mediaDTO,Media.class);
            String  type = ioUtils.getType(file.getOriginalFilename());
            try {
                if(Objects.isNull(type))
                throw new SystemException(AppHttpCodeEnum.MEDIA_TYPE_ERROR);
                String url = ioUtils.uploadMedia(file, IOEnum.IS_MEDIA);
                media.setType(type);
                media.setUrl(url);
                media.setMemberId(SecurityUtils.getLoginUserId());
                media.setUploadTime(new Date());
                mediaMapper.insert(media);
            } catch (SystemException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public List<MediaVO> mediaList() {
        List<Media> media = mediaMapper.selectList(new LambdaQueryWrapper<>());
        List<MediaVO> list = media.stream().map(each -> {
            MediaVO mediaVO = BeanCopyUtils.copyBean(each, MediaVO.class);
            Member member = memberMapper.selectById(each.getMemberId());
            mediaVO.setMemberName(member.getName());
            return mediaVO;
        }).collect(Collectors.toList());
        return list;
    }
}
